using System;
using System.Collections.Generic;
using Common;

public class UnityMainThreadDispatcher : Singleton<UnityMainThreadDispatcher>
{
    private readonly Queue<Action> _actions = new Queue<System.Action>();

    public void Enqueue(Action action)
    {
        lock (_actions)
        {
            _actions.Enqueue(action);
        }
    }

    public void Update()
    {
        lock (_actions)
        {
            while (_actions.Count > 0)
            {
                Action action = null;
                if (_actions.Count > 0)
                {
                    action = _actions.Dequeue();
                }
                
                try
                {
                    action?.Invoke();
                }
                catch (Exception e)
                {
#if UNITY_EDITOR
                    UnityEngine.Debug.LogException(e);
#endif
                }
            }
        }


    }
}